import React from "react";
import style from "./index.module.scss";
import {withRouter} from "react-router-dom";
import MAlert from "../../base/MAlert";
import store from "../../Store";
import {request} from "../../serverAPI/index";

class SocketKeeper extends React.Component{
    constructor(){
        super();
        this.state={
            userinfo:null,
            toUserInfo:null,
            cMessage:null,
            showNotification:false,
            newMsg:null,
        }
        this.sConfig={host:"ws://localhost",port:8206}
        this.currMsgFrom = "",
        this.socket = null;
        this.heart = null;
        this.conn = false;
    }

    /*---this=react 创建通信连接---*/ 
    createWebSocket(){
        console.log("--createWebSocket--")
        this.socket = new WebSocket(this.sConfig.host +":"+this.sConfig.port);
        this.socket.react = this;
        this.socket.addEventListener("open",this.onConnOpen);
        this.socket.addEventListener("close",this.onConnClose);
        this.socket.addEventListener("error",this.onConnError);
        this.socket.addEventListener("message",this.onMsg);
    }
    /*---this=react 创建通信心跳---*/ 
    socketHeart(){
        this.heart = setInterval(() => {
            let {userinfo} = this.state;
            if(!userinfo){
                let temp = localStorage.getItem("userList");
                if(!temp) console.log("未检测到用户登录信息，无法创建通讯连接...");
                else{
                    userinfo = JSON.parse(temp);
                    this.setState({userinfo});
                }
            }else{
                if (!this.conn) {
                    this.createWebSocket();
                    console.log("通讯中断重连 ... ...");
                } else {
                    // console.log(new Date().getTime(),userinfo.uid,"心跳 ... ...");
                    this.socket.send(
                        JSON.stringify({
                            uid: userinfo.uid,
                            type: "heart",
                        })
                    );
                }
            }
        }, 5000);
    }
    /*---this=socket 创建打开---*/ 
    onConnOpen(){
        let {userinfo} = this.react.state;
        console.log("通讯服务器连接成功");
        this.react.conn = true;
        if (!userinfo) {
            // 生成新的用户id,并存入localStorage
            this.uid = 'web_im_^'+userinfo.uid+"^" + moment().valueOf();
            localStorage.setItem('WEB_IM_USER', JSON.stringify({
                uid: userinfo.uid,
                nickname: userinfo.nickname,
                type: "connhandler",
            }));
            this.react.sendConnHandler(userinfo.uid, userinfo.nickname);
        }
    }
    /*---this=socket 创建关闭---*/ 
    onConnClose(){
        console.log("通讯服务器关闭");
        this.react.conn = false;
    }
    /*---this=socket 创建异常---*/ 
    onConnError(err){
        this.react.conn = false;
        console.log("通讯连接出错",err);
    }
    /*---this=react 首次连接信息---*/ 
    sendConnHandler(uid,nickname){
        let connHandlerInfo = {
            uid,
            nickname,
            type: "connhandler",
            msg: "msg-connhandler"
        }
        this.socket.send(JSON.stringify(connHandlerInfo));
    };
    /*---this=socket 接收通信广播---*/
    onMsg(e){
        let {userinfo:userInfo, toUserInfo} = this.react.state;

        let message = JSON.parse(e.data);
        this.react.pullChatRecords(message);

        store.dispatch({type:"ADDMESSAGE",data:message});

        if(message.toUid == userInfo.uid){
            let showNotification = store.getState().lastPathname == "/privateChat";
            this.react.setState({showNotification, newMsg:message})
        }
        return ;

        vm.currMsgFrom = message.message;
        vm.props.addMessage(message);

        vm.openNotification(false);
        setTimeout(()=>{
            if(vm.props.history.location.pathname == "/privateChat") return;
            vm.openNotification(true);
        },100);

        if (vm.uid === message.uid || vm.uid !== message.uid) {
            vm.cargoMsg = message;
            let {msgList} = vm.state;
            if (message.type === "letter" && vm.callMsgAlert)
                vm.callMsgAlert();
            else if (message.type === "chat" && msgList){
               
                // 与自己无关的消息
                let fm = (message.fromUid === userInfo.uid && message.toUid === toUserInfo.uid);
                let tm = (message.fromUid === toUserInfo.uid  && message.toUid === userInfo.uid);
                // if(!fm || !tm) return;

                message.mid = Date.now();
               
                
                // msgList.push(message);
                // vm.setState({msgList});
                // setTimeout(()=>{
                //     try{
                //         if(!vm.msglistWarp) return;
                //         vm.msglistWarp.scrollTo({
                //             top:vm.msglistWarpInner.offsetHeight - vm.msglistWarp.clientHeight,
                //             behavior:"smooth",
                //         });
                //     }catch(err){
                //     }
                // },50)
            }
        }
    }
    /*---this=react 发送信息---*/
    sendMsg(message){
        this.socket.send(JSON.stringify(message));
    }
    /*---this=react 消息提醒---*/
    openNotification(flag){
        if(flag){
            if(this.currMsgFrom || this.currMsgFrom == 0) this.setState({showNotification:true});
        }else{
            this.setState({showNotification:false});
        }
    }

    /*---request 获取消息队列---*/ 
    getMeMessageAll(uid){
        if(!uid) return;
        request({
            url:"/getMeMessageAll?uid="+uid,
            method:"GET",
        }).then(res=>{
            let {code,data} = res.data;
            if(code=="01"){
                store.dispatch({type:"ADDMESSAGE",data})
            }
        });
    }

    pullChatRecords(msgObj){
        request({
            url:"/pullChatRecords",
            method:"POST",
            data:msgObj
        }).then(res=>{
            console.log(res.data);
        });
    }

    goPrivateChat(){
        setTimeout(()=>{
            let friendInfo = this.state.newMsg;
            let {userinfo} = this.state;
            if(!userinfo.uid) return alert("请先登录!");

            this.props.history.push({
                pathname:"/privateChat", 
                state:{
                    toUid: friendInfo.toUid,
                    tnickname: friendInfo.tnickname,
                    thead_url: friendInfo.thead_url,
                    tstuAuth: friendInfo.tstuAuth,
                }
            })
        },200);
    }

    /*---store ------
        1、将数据服务获取的消息队列填充到 仓库消息队列
        2、从仓库 获取发送的 当前消息（监听）
        3、将 当前消息 通过socket 发送，同时清除当前消息
        4、将 通信获取的消息 追加到 仓库消息队列

        // 消息中心
            1、监听仓库的 消息队列 （监听）
            2、分析消息队列，整理出 联系人列表，以及当前联系人是否未读度消息
            3、渲染联系人列表
            4、建立跳转连接
        // 用户对话框
            〇、监控仓库消息队列 （监听）
            一、跳转来源：
                1、消息中心
                    从仓库中获取对应的消息列表
                2、图书详情
                    从数据库中获取相关的消息列表 ？ 
                3、客服中心
                    通过我的页面获取相关客服交流信息
                    从数据库中获取相关的消息列表
            二、发送消息
                将当前消息对象填充到仓库 当前发送消息
            
    */

    componentDidMount(){
        let temp = localStorage.getItem("userList");
        if(!temp) return console.log("未检测到用户登录信息，无法创建通讯连接...");
        let userinfo = JSON.parse(temp);
        this.setState({userinfo});
        // this.socketHeart(); // 建立健康通信
        this.createWebSocket() // 建立简介 无心跳

        setTimeout(()=>{
            this.getMeMessageAll(userinfo.uid);
        },500);

        // if(this.currMsgFrom || this.currMsgFrom == 0){
        //     this.setState({showNotification:true})
        // }else{
        //     this.setState({showNotification:false})
        // }

        this.unsubscribe = store.subscribe(()=>{
            let {currMessage} = store.getState();
            if(currMessage) console.log("keeper-->",currMessage.message)
            if(currMessage) this.sendMsg(currMessage);

            // setTimeout(()=>{
            //     if(currMessage){
            //         store.dispatch({type: "PULLCMESSAGE",data: currMessage})
            //     }
            // },100)
        });
    }
    componentWillUnmount(){
        this.unsubscribe();
        clearInterval(this.heart);
        this.heart = null;
    }

    render(){
        console.log("--->>>",this.currMsgFrom)
        return (
            <div className="SocketKeeper-root">
                {(this.state.showNotification && this.props.location.pathname != "/privateChat" ) &&
                    <MAlert callAlert = {this.openNotification.bind(this)} direction = "right"
                        closeBtnText = "已读"
                        closeBtnStyle = {{borderRadius: "5px", width: "60px", height: "29px",
                        backgroundColor: "#DE7D2C",top:"81px",right:"30px",lineHeight:"30px"}}
                    >
                        <div className={style["alert-body"]}>
                            <p>{this.state.newMsg.fnickname +"："+this.state.newMsg.message}</p>
                            <button
                                // onClick={ this.goPrivateChat.bind(this) }
                            >详情</button>
                        </div>
                    </MAlert>
                }

                <div style={{position:"fixed",height:"0",overflow:"hidden",bottom:"-100px"}}>

                </div>
            </div>
        )
    }
}

export default withRouter(SocketKeeper);